<template>
  <div>
    <el-form
        :model="formData"
        ref="formData"
        label-width="144px"
        class="ccui-form"
        :rules="rules"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgName">
            <el-select
                v-model="formData.reportInOrgName"
                placeholder="请选择填报单位"
                @change="changeReportInOrgId"
            >
              <el-option
                  v-for="item in reportOptions"
                  :key="item.orgId"
                  :label="item.name"
                  :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="部门：" prop="reportOrgDeptName">
            <el-select
                ref="selectReportTree"
                v-model="formData.reportOrgDeptName"
                placeholder="请选择部门"
                popper-class="popperTreeSelect"
            >
              <el-option label="" value="">
                <el-tree
                    :data="reportDeptOptions"
                    :props="{ children: 'child', label: 'abbrName' }"
                    @node-click="handleReportDeptClick"
                >
                  <span
                      :class="{
                      'depart-tree-node': formData.reportOrgDeptName === node.data.abbrName
                    }"
                      slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="移库单编号：" prop="moveInventoryCode">
            <el-input v-model="formData.moveInventoryCode" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移库单名称：" prop="moveInventoryName">
            <el-input
                maxlength="300"
                v-model="formData.moveInventoryName"
                placeholder="请输入移库单名称"
                show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="是否跨项目：" prop="isAcrossProject">
            <el-radio-group v-model="formData.isAcrossProject" @change="getChange">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类名称：" prop="categoryName">
            <el-input v-model="formData.categoryName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="原仓库：" prop="originalWarehouseName">
            <el-input
                v-model="formData.originalWarehouseName"
                placeholder="请选择原仓库"
                disabled
            />
            <el-button
                plain
                type="single-number"
                style="margin-left: 10px"
                @click="handleOrgHouse"
            >选择
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标仓库：" prop="targetWarehouseName">
            <el-input
                v-model="formData.targetWarehouseName"
                placeholder="请选择目标仓库"
                disabled
            />
            <el-button
                plain
                type="single-number"
                style="margin-left: 10px"
                @click="handleAimHouse"
            >选择
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!--目标仓库、附件张数-->
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="目标单位部门：" prop="targetOrgDeptName">
            <el-select
                ref="selectTargetTree"
                v-model="formData.targetOrgDeptName"
                placeholder="请选择目标单位部门"
                popper-class="popperTreeSelect"
            >
              <el-option label="" value="">
                <el-tree
                    :data="targetDeptOptions"
                    :props="{ children: 'child', label: 'abbrName' }"
                    @node-click="handleTargetDeptClick"
                >
                  <span
                      :class="{
                      'depart-tree-node': formData.targetOrgDeptName === node.data.abbrName
                    }"
                      slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="附件张数：" prop="filesNumber">
            <el-input @input="(val)=>{formData.filesNumber = val.replace(/[^\d]/g, '')}" v-model="formData.filesNumber"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="移库数量：" prop="moveInventoryCount">
            <el-input v-model="formData.moveInventoryCount" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移库金额：" prop="moveInventoryMoney">
            <el-input v-model="formData.moveInventoryMoney" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="编制人：" prop="reportUsername">
            <el-input v-model="formData.reportUsername" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编制日期：" prop="reportTime">
            <el-date-picker
                v-model="formData.reportTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="19">
          <el-form-item label="业务事由：" prop="businessReason">
            <el-input
                type="textarea"
                :rows="5"
                maxlength="1000"
                show-word-limit
                placeholder="请输入业务事由"
                v-model="formData.businessReason"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="19">
          <el-form-item label="备注：" prop="remark">
            <el-input
                type="textarea"
                :rows="5"
                maxlength="1000"
                show-word-limit
                placeholder="请输入备注"
                v-model="formData.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <org-house
        ref="orgHouse"
        :reportInOrgId="formData.reportInOrgId"
        :reportInOrgName="formData.reportInOrgName"
        :isTrue="false"
        @getRow="getRow"
    />
    <aim-house
        ref="aimHouse"
        :reportInOrgId="formData.reportInOrgId"
        :reportInOrgName="formData.reportInOrgName"
        :isAcrossProject="formData.isAcrossProject"
        :isTrue="false"
        @getAim="getAim"
        @getAccrossProject="getAccrossProject"
    />
  </div>
</template>

<script>
import {getUserInfo, getReportInOrgData, qryUnderOrg} from "@/basa/api";
import {addUrlPerFix} from "@/basa/utils";
import orgHouse from "./orgHouse.vue";
import aimHouse from "./aimHouse.vue";
import {mapActions} from "vuex";

export default {
  components: {orgHouse, aimHouse},
  data() {
    return {
      formData: {
        reportInOrgName: "", //填报单位
        reportInOrgId: null, //填报单位id
        reportInOrgCode: "", //填报单位code
        categoryName: "", //分类名称
        categoryCode: "", //分类名称编码
        moveInventoryName: "", //移库单名称
        moveInventoryCode: "", //移库单编号
        originalWarehouseName: "", //原仓库
        originalWarehouseId: null, //原仓库id
        originalWarehouseCode: "", //原仓库编码
        targetWarehouseName: "", //目标仓库
        targetWarehouseId: null, //目标仓库id
        targetWarehouseCode: "", //目标仓库编码
        moveInventoryCount: "", //移库数量
        moveInventoryMoney: "", //移库金额
        reportUsername: "", //编制人
        reportOpenid: "", //编制人id
        reportTime: "", //编制日期
        remark: "", //备注
        isAcrossProject: 0,//是否跨项目 是：1，否：0
        businessReason: "",//业务事由
        reportOrgDeptName: "",//填报单位部门名称
        reportInDeptCode: "",//填报单位部门编码
        reportOrgDeptId: "",//填报单位部门id
        reportInDeptExtcode: "",//填报单位部门4a编码
        targetOrgDeptId: "",//目标单位部门id
        targetInDeptCode: "",//目标单位部门编码
        targetOrgDeptName: "",//目标单位部门名称
        targetInDeptExtcode: "",//目标单位部门4a编码
        targetInOrgId: "",//目标单位orgid
        targetInOrgCode: "",//目标单位编码
        targetInOrgName: "",//目标单位名称
        filesNumber: "",//附件张数
      },
      rules: {
        reportInOrgName: [
          {
            required: true,
            message: "请选择填报单位",
            trigger: "change"
          }
        ],
        originalWarehouseName: [
          {
            required: true,
            message: "请选择原仓库",
            trigger: "change"
          }
        ],
        targetWarehouseName: [
          {
            required: true,
            message: "请选择目标仓库",
            trigger: "change"
          }
        ],
        targetOrgDeptName: [
          {
            required: true,
            message: "请选择目标单位部门",
            trigger: "change"
          }
        ],
        reportOrgDeptName: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change"
          }
        ],
        moveInventoryName: [
          {
            required: true,
            message: "请输入移库单名称",
            trigger: "change"
          }
        ],
        isAcrossProject: [
          {
            required: true,
            message: "请选择是否跨单位",
            trigger: "blur"
          }
        ],
        businessReason: [
          {
            required: true,
            message: "请输入业务事由",
            trigger: "blur"
          }
        ],
        filesNumber: [
          {
            required: true,
            message: "请输入附件张数",
            trigger: "blur"
          },
        ],
      },
      reportInOrgObj: {
        title: "填报单位查询",
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 10
        }
      },
      reportOptions: [], // 填报单位
      reportDeptOptions: [], // 部门
      targetDeptOptions: [], // 目标部门
      showAim: false
    };
  },
  watch: {
    "formData.reportInOrgName": {
      handler(n) {
        if (n) {
          const tempObj = this.reportOptions.find(e => e.name === n);
          if (tempObj) {
            this.formData.reportInOrgId = tempObj.orgId;
            this.formData.reportInOrgName = tempObj.name;
            this.formData.reportInOrgCode = tempObj.autoCode;
          }
        }
      },
      immediate: true,
      deep: true
    },
    'formData.isAcrossProject'(value) {
      //    是
      //    if(value == '1'){

      //    }else if(value == '0'){

      //    }
    },
    moveInventoryCount: {
      immediate: true,
      handler: function (a, b) {
        // console.log(a,b);
        this.formData.moveInventoryCount = a;
      }
    },
    moveInventoryMoney: {
      immediate: true,
      handler: function (a, b) {
        console.log(a, b);
        this.formData.moveInventoryMoney = a;
      }
    }
  },
  mounted() {
  },
  methods: {
    // 原仓库
    handleOrgHouse() {
      if (this.$refs.orgHouse.reportInOrgId) {
        this.$refs.orgHouse.dialogVisible = true;
        this.$refs.orgHouse.getContractList(this.$refs.orgHouse.formData);
      } else {
        this.$showErrorMessage("请先选择填报单位！");
      }
    },
    // 获取原仓库
    getRow(message) {
      console.log(message);
      this.formData.originalWarehouseName = message.warehouseName;
      this.formData.originalWarehouseId = message.id;
      this.formData.originalWarehouseCode = message.warehouseCode;
      this.$emit("getRowOrg", message);
      this.setInventoryStatus(!!message.warehouseName);
      if (this.formData.targetWarehouseId && message.id == this.formData.targetWarehouseId) {
        this.$showErrorMessage("原仓库不能与目标仓库相同，请重新选择！");
        this.formData.originalWarehouseName = ''
        this.formData.originalWarehouseId = null
        this.formData.originalWarehouseCode = '';
      }
    },
    // 目标仓库
    handleAimHouse() {
      if (this.formData.isAcrossProject == "0") {
        this.$refs.aimHouse.dialogVisible = true;
        this.$refs.aimHouse.getList();
      } else if (this.formData.isAcrossProject == "1") {
        this.$refs.aimHouse.$refs.staffSelector.isShow = true;
        this.$refs.aimHouse.getContractList(this.$refs.aimHouse.formData);
      }
    },
    // 获取目标仓库
    getAim(message) {
      console.log("getAim", message)
      this.formData.targetWarehouseName = message.warehouseName;
      this.formData.targetWarehouseId = message.id;
      this.formData.targetWarehouseCode = message.warehouseCode;
      // 存入目标单位数据
      this.formData.targetInOrgId = message.reportInOrgId;
      this.formData.targetInOrgCode = message.reportInOrgCode;
      this.formData.targetInOrgName = message.reportInOrgName;
      this.$emit("getRowAim", message);
      this.setInventoryStatus(!!message.warehouseName);
      if (message.id == this.formData.originalWarehouseId) {
        this.$showErrorMessage("目标仓库不能与原仓库相同，请重新选择！");
        this.formData.targetWarehouseName = "";
        this.formData.targetWarehouseId = null;
        this.formData.targetWarehouseCode = "";
      } else {
        // 获取目标单位部门数据
        this.getTargetDepartData(message.reportInOrgId);
      }
    },
    // 重置跨单位
    getAccrossProject(data) {
      this.formData.isAcrossProject = data;
    },
    getChange() {
      this.formData.targetWarehouseName = "";//目标仓库
      this.formData.targetWarehouseId = null;
      // 清空目标单位部门 以及目标单位
      this.formData.targetInDeptCode = "";
      this.formData.targetOrgDeptName = "";
      this.formData.targetOrgDeptId = "";
      this.formData.targetInDeptExtcode = "";
      this.formData.targetInOrgId = "";
      this.formData.targetInOrgCode = "";
      this.formData.targetInOrgName = "";
      this.targetDeptOptions = [];
    },
    // 获取当前日期
    addDate() {
      let nowDate = new Date();
      let date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      };
      this.formData.reportTime = date.year + "/" + date.month + "/" + date.date;
    },
    // 获取详情
    getUserInfo() {
      getUserInfo(
          addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
          {}
      ).then(res => {
        this.formData.reportUsername = res.data.data.userInfo.name;
        this.formData.reportOpenid = res.data.data.userInfo.id; //编制人id

        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报单位信息
    getReportInOrgData(openId) {
      getReportInOrgData({openIds: [openId]}).then(res => {
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.formData.reportInOrgName =
            this.formData.reportInOrgName || this.reportOptions[0].name;
        this.formData.reportInOrgId =
            this.formData.reportInOrgId || this.reportOptions[0].orgId;
        this.formData.reportInOrgCode =
            this.formData.reportInOrgCode || this.reportOptions[0].autoCode;
        // 加载填报部门数据
        this.getDepartData(this.reportOptions[0].orgId);
      });
    },
    changeReportInOrgId(val) {
      const tempObj = this.reportOptions.find(e => e.name === val);
      this.formData.reportInOrgId = tempObj.orgId;
      this.formData.reportInOrgName = tempObj.name;
      this.formData.reportInOrgCode = tempObj.autoCode;
      this.formData.categoryName = "";
      this.formData.categoryCode = "";
      this.formData.originalWarehouseName = "";
      this.formData.originalWarehouseId = null;
      this.formData.originalWarehouseCode = "";
      this.formData.moveInventoryCount = "";
      this.formData.moveInventoryMoney = "";
      let tableData = [];
      this.getDepartData(tempObj.orgId);
      this.$bus.$emit("resetPurchase", tableData);
      this.setInventoryStatus(false);
    },

    // 填报单位部门 start
    async getDepartData(parentId) {
      const {
        child,
        child: [{id, abbrName, autoCode, extOid}]
      } = (
          await qryUnderOrg({
            parentId, // 全局 其他【此组件是本级及以下】
            flag: "1" // 0 公司 1 部门 2 成员
          })
      ).data.data[0];
      this.reportDeptOptions = child;
      // 默认第一个部门
      this.formData.reportOrgDeptId = id;
      this.formData.reportOrgDeptName = abbrName;
      this.formData.reportInDeptCode = autoCode;
      this.formData.reportInDeptExtcode = extOid;
    },
    // 填报单位部门选中的数据
    handleReportDeptClick({id, abbrName, autoCode, extOid}) {
      this.formData.reportOrgDeptId = id;
      this.formData.reportOrgDeptName = abbrName;
      this.formData.reportInDeptCode = autoCode;
      this.formData.reportInDeptExtcode = extOid;
      this.$refs.selectReportTree.blur();
    },
    // 填报单位部门 end

    // 目标单位部门 start
    async getTargetDepartData(parentId) {
      const {
        child,
        child: [{id, abbrName, autoCode, extOid}]
      } = (
          await qryUnderOrg({
            parentId, // 全局 其他【此组件是本级及以下】
            flag: "1" // 0 公司 1 部门 2 成员
          })
      ).data.data[0];
      console.log('parentId', parentId);
      this.targetDeptOptions = child;
      // 默认第一个部门
      this.formData.targetOrgDeptId = id;
      this.formData.targetOrgDeptName = abbrName;
      this.formData.targetInDeptCode = autoCode;
      this.formData.targetInDeptExtcode = extOid;
    },

    // 目标单位部门选中的数据
    handleTargetDeptClick({id, abbrName, autoCode, extOid}) {
      this.formData.targetOrgDeptId = id;
      this.formData.targetOrgDeptName = abbrName;
      this.formData.targetInDeptCode = autoCode;
      this.formData.targetInDeptExtcode = extOid;
      this.$refs.selectTargetTree.blur();
    },
    // 目标单位部门 end
    ...mapActions(["setInventoryStatus"])
  },
  computed: {
    moveInventoryCount() {
      return this.$store.state.moveStore.moveInventoryCount;
    },
    moveInventoryMoney() {
      return this.$store.state.moveStore.moveInventoryMoney;
    }
  },

  created() {
    // this.formData.moveInventoryCount = this.moveInventoryCount;
    // this.formData.moveInventoryMoney = this.moveInventoryMoney;

    this.getUserInfo();
    this.addDate();
    // 分类名称
    this.$bus.$on("getCategoryName", message => {
      this.$set(this.formData, "categoryName", message.categoryName);
      this.$set(this.formData, "categoryCode", message.categoryCode);
    });

    // 移库数量
    // this.$bus.$on("getMoveNum", (message) => {
    // this.$set(this.formData, "moveInventoryCount", this.moveInventoryCount);
    // // 移库金额
    // this.$bus.$on("getMoveMoney", (message) => {
    // this.$set(this.formData, "moveInventoryMoney", this.moveInventoryMoney);
    // });
  },
  activated() {
    this.$refs.formData.resetFields();

    this.addDate();
    this.getUserInfo();
    // this.$set(this.formData, "reportTime", new Date());
    console.log(this.formData.reportTime);
  },
  deactivated() {
    this.$store.commit("setMoveInventoryCount", "");
    this.$store.commit("setMoveInventoryMoney", "");
    this.formData.moveInventoryCount = "";
    this.formData.setMoveInventoryMoney = "";
    // this.$bus.$off("getCategoryName");
    // this.$bus.$off("getMoveNum");
    // this.$bus.$off("getMoveMoney");
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-input {
  width: 260px;
}

.ccui-form {
  margin: 20px 0 70px 50px;

  &::v-deep {
    .el-input input {
      padding-right: 50px;
    }
  }
}
</style>
